package com.oceansoft.core.jxkh.controller;

import com.oceansoft.core.jxkh.dao.ImageInDBDao;
import com.oceansoft.core.jxkh.domain.Photo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by OS on 2017/12/7.
 */

@Controller
public class ImageController {
    @Resource
    private ImageInDBDao imageInDBDao;

    @RequestMapping(value = "inImage.html",produces = "text/html;charset=UTF-8")
    public void inImage(){
        String path = "D://photo";
        imageInDBDao.ImageIn(path);
    }
    @RequestMapping(value = "outImage.html",produces = "text/html;charset=UTF-8")
    public void outImage() {
        String path = "D://newPhoto";
        List<Photo> list = imageInDBDao.ImageOut();
        System.out.println(list.size());
        int i = 0;
        for (Photo photo:list) {
            if(!GenerateImage(photo,path))
                break;
            i++;
        }
    }

    //base64字符串转化成图片
    public static boolean GenerateImage(Photo photo,String path)
    {
        //对字节数组字符串进行Base64解码并生成图片
        if (photo.getPhoto() == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(photo.getPhoto());
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = path+"/"+photo.getName();//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

}
